package com.bwie.task;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.Es.EsProd;
import com.bwie.mapper.TbProdMapper;
import com.bwie.pojo.TbProd;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author: zhaijiaqi
 * @Date: 2025/7/1 14:54
 * @Description:
 **/
@Component
public class SyncTestToEs {

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    TbProdMapper tbProdMapper;



    @Scheduled(cron = "0 0/1 * * * ?")
    public void TestProdToEs(){
        System.out.println("开始执行定时任务");
        //第一步创建索引
        IndexOperations indexOps = elasticsearchRestTemplate.indexOps(EsProd.class);
        boolean exists = indexOps.exists();
        if(!exists){
            indexOps.create();
            Document mapping = indexOps.createMapping();
            indexOps.putMapping(mapping);
        }
        Page<TbProd> page = new Page<>(1,100000);

        Page<TbProd> tbProdPage = tbProdMapper.selectPageProd(page, null);
        List<TbProd> records = tbProdPage.getRecords();
        for (TbProd record : records) {
            EsProd esProd = BeanUtil.toBean(record, EsProd.class);
            elasticsearchRestTemplate.save(esProd);
        }
        System.out.println("定时任务执行结束");

    }
}
